<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="副本集MongoDB复制是将数据同步在多个服务器的过程。 复制提供了数据的冗余备份，并在多个服务器上存储数据副本，提高了数据的可用性， 并可以保证数据的安全性。 复制还允许您从硬件故障和服务中断中恢复数据。 什么是复制? 保障数据的安全性 数据高可用性 (24*7) 灾难恢复 无需停机维护（如备份，重建索引，压缩） 分布式读取数据">
<meta name="keywords" content="Mongo">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB5-副本集">
<meta property="og:url" content="http://www.saily.top/2018/01/07/mongo5/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="副本集MongoDB复制是将数据同步在多个服务器的过程。 复制提供了数据的冗余备份，并在多个服务器上存储数据副本，提高了数据的可用性， 并可以保证数据的安全性。 复制还允许您从硬件故障和服务中断中恢复数据。 什么是复制? 保障数据的安全性 数据高可用性 (24*7) 灾难恢复 无需停机维护（如备份，重建索引，压缩） 分布式读取数据">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/replica-set-primary-with-two-secondaries.bakedsvg.svg">
<meta property="og:updated_time" content="2018-01-27T03:24:50.019Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB5-副本集">
<meta name="twitter:description" content="副本集MongoDB复制是将数据同步在多个服务器的过程。 复制提供了数据的冗余备份，并在多个服务器上存储数据副本，提高了数据的可用性， 并可以保证数据的安全性。 复制还允许您从硬件故障和服务中断中恢复数据。 什么是复制? 保障数据的安全性 数据高可用性 (24*7) 灾难恢复 无需停机维护（如备份，重建索引，压缩） 分布式读取数据">
<meta name="twitter:image" content="https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/01/07/mongo5/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB5-副本集 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/01/07/mongo5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB5-副本集
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-07T18:47:46+08:00">1月 7 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Mongo/" itemprop="url" rel="index"><span itemprop="name">Mongo</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="副本集"><a href="#副本集" class="headerlink" title="副本集"></a>副本集</h1><p>MongoDB复制是将数据同步在多个服务器的过程。</p>
<p>复制提供了数据的冗余备份，并在多个服务器上存储数据副本，提高了数据的可用性， 并可以保证数据的安全性。</p>
<p>复制还允许您从硬件故障和服务中断中恢复数据。</p>
<h2 id="什么是复制"><a href="#什么是复制" class="headerlink" title="什么是复制?"></a>什么是复制?</h2><ul>
<li>保障数据的安全性</li>
<li>数据高可用性 (24*7)</li>
<li>灾难恢复</li>
<li>无需停机维护（如备份，重建索引，压缩）</li>
<li>分布式读取数据</li>
</ul>
<a id="more"></a>
<h2 id="MongoDB复制原理"><a href="#MongoDB复制原理" class="headerlink" title="MongoDB复制原理"></a>MongoDB复制原理</h2><p>mongodb的复制至少需要两个节点。其中一个是主节点，负责处理客户端请求，其余的都是从节点，负责复制主节点上的数据。</p>
<p>mongodb各个节点常见的搭配方式为：一主一从、一主多从。</p>
<p>主节点记录在其上的所有操作oplog，从节点定期轮询主节点获取这些操作，然后对自己的数据副本执行这些操作，从而保证从节点的数据与主节点一致。</p>
<p>MongoDB复制结构图如下所示：</p>
<p><img src="https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg" alt=""></p>
<p><img src="https://docs.mongodb.com/manual/_images/replica-set-primary-with-two-secondaries.bakedsvg.svg" alt=""></p>
<p>以上结构图中，客户端从主节点读取数据，在客户端写入数据到主节点时， 主节点与从节点进行数据交互保障数据的一致性。</p>
<h2 id="副本集特征："><a href="#副本集特征：" class="headerlink" title="副本集特征："></a>副本集特征：</h2><ul>
<li>N个节点的集群</li>
<li>任何节点可作为主节点</li>
<li>所有写入操作都在主节点上</li>
<li>自动故障转移</li>
<li>自动恢复</li>
</ul>
<h2 id="MongoDB副本集配置"><a href="#MongoDB副本集配置" class="headerlink" title="MongoDB副本集配置"></a>MongoDB副本集配置</h2><ol>
<li>MongoDB数据文件存储路径</li>
<li>MongoDB日志文件存储路径</li>
<li>MongoBD key文件存储路径</li>
<li>MongoDB实例监听端口（28010/28011/28012）</li>
</ol>
<p>先把要存储的目录和文件先建一下，key0，key1，key2的文件内容是一样的。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">.</span><br><span class="line">├── data</span><br><span class="line">│   ├── data0</span><br><span class="line">│   ├── data1</span><br><span class="line">│   └── data2</span><br><span class="line">├── key</span><br><span class="line">│   ├── key0</span><br><span class="line">│   │   └── key0</span><br><span class="line">│   ├── key1</span><br><span class="line">│   │   └── key1</span><br><span class="line">│   └── key2</span><br><span class="line">│       └── key2</span><br><span class="line">└── <span class="built_in">log</span></span><br><span class="line">    ├── log0</span><br><span class="line">    │   └── log0.log</span><br><span class="line">    ├── log1</span><br><span class="line">    │   └── log1.log</span><br><span class="line">    └── log2</span><br><span class="line">        └── log2.log</span><br></pre></td></tr></table></figure>
<p>启动3个mongod实例的副本集</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mongod --replSet myset --keyFile key/key0/key0 --port 28010 --dbpath data/data0 --logpath log/log0/log0.log --logappend</span><br><span class="line">mongod --replSet myset --keyFile key/key1/key1 --port 28011 --dbpath data/data1 --logpath log/log1/log1.log --logappend</span><br><span class="line">mongod --replSet myset --keyFile key/key2/key2 --port 28012 --dbpath data/data2 --logpath log/log2/log2.log --logappend</span><br></pre></td></tr></table></figure>
<p>启动可能会有一个错误：</p>
<blockquote>
<p>mongodb/key/key0/key0 are too open</p>
</blockquote>
<p>查了一下说是key的文件权限太大了，<code>chmod 700 key/key0/key0</code>改一下权限再启动就好了。</p>
<p>现在这3个mongod的实例还没有通信，还没有在一个副本集中，还需要用客户端连接到其中一个实例做一些配置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">mongo --port <span class="number">28010</span></span><br><span class="line">&gt; config_myset=&#123;<span class="attr">_id</span>:<span class="string">'bafeite'</span>, <span class="attr">members</span>:[&#123;<span class="attr">_id</span>:<span class="number">0</span>, <span class="attr">host</span>:<span class="string">'localhost:28010'</span>&#125;,&#123;<span class="attr">_id</span>:<span class="number">1</span>, <span class="attr">host</span>:<span class="string">'localhost:28011'</span>&#125;,&#123;<span class="attr">_id</span>:<span class="number">2</span>, <span class="attr">host</span>:<span class="string">'localhost:28012'</span>&#125;]&#125;;</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"_id"</span> : <span class="string">"bafeite"</span>,</span><br><span class="line">	<span class="string">"members"</span> : [</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28010"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28011"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28012"</span></span><br><span class="line">		&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line">&gt; rs.initiate(config_myset);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"errmsg"</span> : <span class="string">"Attempting to initiate a replica set with name bafeite, but command line reports myset; rejecting"</span>,</span><br><span class="line">	<span class="string">"code"</span> : <span class="number">93</span>,</span><br><span class="line">	<span class="string">"codeName"</span> : <span class="string">"InvalidReplicaSetConfig"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>出错了，说准备初始化一个bafeite的副本集，但是命令行启动的时候是<code>myset</code>，所以拒绝。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br></pre></td><td class="code"><pre><span class="line">&gt; config_myset=&#123;<span class="attr">_id</span>:<span class="string">'myset'</span>, <span class="attr">members</span>:[&#123;<span class="attr">_id</span>:<span class="number">0</span>, <span class="attr">host</span>:<span class="string">'localhost:28010'</span>&#125;,&#123;<span class="attr">_id</span>:<span class="number">1</span>, <span class="attr">host</span>:<span class="string">'localhost:28011'</span>&#125;,&#123;<span class="attr">_id</span>:<span class="number">2</span>, <span class="attr">host</span>:<span class="string">'localhost:28012'</span>&#125;]&#125;;</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"_id"</span> : <span class="string">"myset"</span>,</span><br><span class="line">	<span class="string">"members"</span> : [</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28010"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28011"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"host"</span> : <span class="string">"localhost:28012"</span></span><br><span class="line">		&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line">&gt; rs.initiate(config_myset);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"operationTime"</span> : Timestamp(<span class="number">1515328983</span>, <span class="number">1</span>),</span><br><span class="line">	<span class="string">"$clusterTime"</span> : &#123;</span><br><span class="line">		<span class="string">"clusterTime"</span> : Timestamp(<span class="number">1515328983</span>, <span class="number">1</span>),</span><br><span class="line">		<span class="string">"signature"</span> : &#123;</span><br><span class="line">			<span class="string">"hash"</span> : BinData(<span class="number">0</span>,<span class="string">"AAAAAAAAAAAAAAAAAAAAAAAAAAA="</span>),</span><br><span class="line">			<span class="string">"keyId"</span> : NumberLong(<span class="number">0</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">&gt; rs.isMaster();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"hosts"</span> : [</span><br><span class="line">		<span class="string">"localhost:28010"</span>,</span><br><span class="line">		<span class="string">"localhost:28011"</span>,</span><br><span class="line">		<span class="string">"localhost:28012"</span></span><br><span class="line">	],</span><br><span class="line">	<span class="string">"setName"</span> : <span class="string">"myset"</span>,</span><br><span class="line">	<span class="string">"setVersion"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"ismaster"</span> : <span class="literal">true</span>,</span><br><span class="line">	<span class="string">"secondary"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"primary"</span> : <span class="string">"localhost:28010"</span>,</span><br><span class="line">	<span class="string">"me"</span> : <span class="string">"localhost:28010"</span>,</span><br><span class="line">	<span class="string">"electionId"</span> : ObjectId(<span class="string">"7fffffff0000000000000001"</span>),</span><br><span class="line">	<span class="string">"lastWrite"</span> : &#123;</span><br><span class="line">		<span class="string">"opTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329025</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"lastWriteDate"</span> : ISODate(<span class="string">"2018-01-07T12:43:45Z"</span>),</span><br><span class="line">		<span class="string">"majorityOpTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329025</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"majorityWriteDate"</span> : ISODate(<span class="string">"2018-01-07T12:43:45Z"</span>)</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"maxBsonObjectSize"</span> : <span class="number">16777216</span>,</span><br><span class="line">	<span class="string">"maxMessageSizeBytes"</span> : <span class="number">48000000</span>,</span><br><span class="line">	<span class="string">"maxWriteBatchSize"</span> : <span class="number">100000</span>,</span><br><span class="line">	<span class="string">"localTime"</span> : ISODate(<span class="string">"2018-01-07T12:43:49.070Z"</span>),</span><br><span class="line">	<span class="string">"logicalSessionTimeoutMinutes"</span> : <span class="number">30</span>,</span><br><span class="line">	<span class="string">"minWireVersion"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"maxWireVersion"</span> : <span class="number">6</span>,</span><br><span class="line">	<span class="string">"readOnly"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"operationTime"</span> : Timestamp(<span class="number">1515329025</span>, <span class="number">1</span>),</span><br><span class="line">	<span class="string">"$clusterTime"</span> : &#123;</span><br><span class="line">		<span class="string">"clusterTime"</span> : Timestamp(<span class="number">1515329025</span>, <span class="number">1</span>),</span><br><span class="line">		<span class="string">"signature"</span> : &#123;</span><br><span class="line">			<span class="string">"hash"</span> : BinData(<span class="number">0</span>,<span class="string">"PnIvjYWgF8Z6qEIViYwQHnBs/M8="</span>),</span><br><span class="line">			<span class="string">"keyId"</span> : NumberLong(<span class="string">"6508288476205547521"</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">&gt; rs.status();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"set"</span> : <span class="string">"myset"</span>,</span><br><span class="line">	<span class="string">"date"</span> : ISODate(<span class="string">"2018-01-07T12:50:20.742Z"</span>),</span><br><span class="line">	<span class="string">"myState"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"term"</span> : NumberLong(<span class="number">1</span>),</span><br><span class="line">	<span class="string">"heartbeatIntervalMillis"</span> : NumberLong(<span class="number">2000</span>),</span><br><span class="line">	<span class="string">"optimes"</span> : &#123;</span><br><span class="line">		<span class="string">"lastCommittedOpTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"readConcernMajorityOpTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"appliedOpTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"durableOpTime"</span> : &#123;</span><br><span class="line">			<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"members"</span> : [</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"localhost:28010"</span>,</span><br><span class="line">			<span class="string">"health"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"state"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"stateStr"</span> : <span class="string">"PRIMARY"</span>,</span><br><span class="line">			<span class="string">"uptime"</span> : <span class="number">2022</span>,</span><br><span class="line">			<span class="string">"optime"</span> : &#123;</span><br><span class="line">				<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">				<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"optimeDate"</span> : ISODate(<span class="string">"2018-01-07T12:50:15Z"</span>),</span><br><span class="line">			<span class="string">"electionTime"</span> : Timestamp(<span class="number">1515328993</span>, <span class="number">1</span>),</span><br><span class="line">			<span class="string">"electionDate"</span> : ISODate(<span class="string">"2018-01-07T12:43:13Z"</span>),</span><br><span class="line">			<span class="string">"configVersion"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"self"</span> : <span class="literal">true</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"localhost:28011"</span>,</span><br><span class="line">			<span class="string">"health"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"state"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"stateStr"</span> : <span class="string">"SECONDARY"</span>,</span><br><span class="line">			<span class="string">"uptime"</span> : <span class="number">437</span>,</span><br><span class="line">			<span class="string">"optime"</span> : &#123;</span><br><span class="line">				<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">				<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"optimeDurable"</span> : &#123;</span><br><span class="line">				<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">				<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"optimeDate"</span> : ISODate(<span class="string">"2018-01-07T12:50:15Z"</span>),</span><br><span class="line">			<span class="string">"optimeDurableDate"</span> : ISODate(<span class="string">"2018-01-07T12:50:15Z"</span>),</span><br><span class="line">			<span class="string">"lastHeartbeat"</span> : ISODate(<span class="string">"2018-01-07T12:50:20.450Z"</span>),</span><br><span class="line">			<span class="string">"lastHeartbeatRecv"</span> : ISODate(<span class="string">"2018-01-07T12:50:20.416Z"</span>),</span><br><span class="line">			<span class="string">"pingMs"</span> : NumberLong(<span class="number">0</span>),</span><br><span class="line">			<span class="string">"syncingTo"</span> : <span class="string">"localhost:28010"</span>,</span><br><span class="line">			<span class="string">"configVersion"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"localhost:28012"</span>,</span><br><span class="line">			<span class="string">"health"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"state"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"stateStr"</span> : <span class="string">"SECONDARY"</span>,</span><br><span class="line">			<span class="string">"uptime"</span> : <span class="number">437</span>,</span><br><span class="line">			<span class="string">"optime"</span> : &#123;</span><br><span class="line">				<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">				<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"optimeDurable"</span> : &#123;</span><br><span class="line">				<span class="string">"ts"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">				<span class="string">"t"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"optimeDate"</span> : ISODate(<span class="string">"2018-01-07T12:50:15Z"</span>),</span><br><span class="line">			<span class="string">"optimeDurableDate"</span> : ISODate(<span class="string">"2018-01-07T12:50:15Z"</span>),</span><br><span class="line">			<span class="string">"lastHeartbeat"</span> : ISODate(<span class="string">"2018-01-07T12:50:20.450Z"</span>),</span><br><span class="line">			<span class="string">"lastHeartbeatRecv"</span> : ISODate(<span class="string">"2018-01-07T12:50:20.367Z"</span>),</span><br><span class="line">			<span class="string">"pingMs"</span> : NumberLong(<span class="number">0</span>),</span><br><span class="line">			<span class="string">"syncingTo"</span> : <span class="string">"localhost:28010"</span>,</span><br><span class="line">			<span class="string">"configVersion"</span> : <span class="number">1</span></span><br><span class="line">		&#125;</span><br><span class="line">	],</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"operationTime"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">	<span class="string">"$clusterTime"</span> : &#123;</span><br><span class="line">		<span class="string">"clusterTime"</span> : Timestamp(<span class="number">1515329415</span>, <span class="number">1</span>),</span><br><span class="line">		<span class="string">"signature"</span> : &#123;</span><br><span class="line">			<span class="string">"hash"</span> : BinData(<span class="number">0</span>,<span class="string">"ADhHuvIZC6jbKdSh8pH00VK+6ic="</span>),</span><br><span class="line">			<span class="string">"keyId"</span> : NumberLong(<span class="string">"6508288476205547521"</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>members就是副本集里面的mongod实例，stateStr表示了实例是Primary或者Secondary，lastHeartbeat就是上次心跳检测的时间。</p>
<h2 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.save(&#123;<span class="attr">title</span>:<span class="string">'MongoDB应用开发实战'</span>, <span class="attr">author</span>:<span class="string">'zhangsan'</span>, <span class="attr">creationDate</span>:<span class="keyword">new</span> <span class="built_in">Date</span>()&#125;);</span><br><span class="line">WriteResult(&#123;</span><br><span class="line">	<span class="string">"writeError"</span> : &#123;</span><br><span class="line">		<span class="string">"code"</span> : <span class="number">13</span>,</span><br><span class="line">		<span class="string">"errmsg"</span> : <span class="string">"not authorized on mytest to execute command &#123; insert: \"article\", ordered: true, $clusterTime: &#123; clusterTime: Timestamp(1515329415, 1), signature: &#123; hash: BinData(0, 003847BAF2190BA8DB29D4A1F291F4D152BEEA27), keyId: 6508288476205547521 &#125; &#125;, $db: \"mytest\" &#125;"</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>得到一个错误，查了下是因为指定了keyFile以后，mongodb默认就会加上<code>--auth</code>启动，为了简化操作，先把keyFile参数去掉重启一下吧。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">~ mongo --port <span class="number">28010</span></span><br><span class="line">use mytest;</span><br><span class="line">myset:PRIMARY&gt; db.article.save(&#123;<span class="attr">title</span>:<span class="string">'MongoDB应用开发实战'</span>, <span class="attr">author</span>:<span class="string">'zhangsan'</span>, <span class="attr">creationDate</span>:<span class="keyword">new</span> <span class="built_in">Date</span>()&#125;);</span><br></pre></td></tr></table></figure>
<p>现在去连接另外一个mongod实例，看看这个数据在不在。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">mongo --port <span class="number">28011</span></span><br><span class="line">use mytest;</span><br><span class="line">show dbs;</span><br><span class="line">myset:SECONDARY&gt; show dbs;</span><br><span class="line"><span class="number">2018</span><span class="number">-01</span><span class="number">-07</span>T21:<span class="number">41</span>:<span class="number">21.587</span>+<span class="number">0800</span> E QUERY    [thread1] <span class="built_in">Error</span>: listDatabases failed:&#123;</span><br><span class="line">	<span class="string">"operationTime"</span> : Timestamp(<span class="number">1515332475</span>, <span class="number">1</span>),</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"errmsg"</span> : <span class="string">"not master and slaveOk=false"</span>,</span><br><span class="line">	<span class="string">"code"</span> : <span class="number">13435</span>,</span><br><span class="line">	<span class="string">"codeName"</span> : <span class="string">"NotMasterNoSlaveOk"</span>,</span><br><span class="line">	<span class="string">"$clusterTime"</span> : &#123;</span><br><span class="line">		<span class="string">"clusterTime"</span> : Timestamp(<span class="number">1515332475</span>, <span class="number">1</span>),</span><br><span class="line">		<span class="string">"signature"</span> : &#123;</span><br><span class="line">			<span class="string">"hash"</span> : BinData(<span class="number">0</span>,<span class="string">"AAAAAAAAAAAAAAAAAAAAAAAAAAA="</span>),</span><br><span class="line">			<span class="string">"keyId"</span> : NumberLong(<span class="number">0</span>)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行不了，报错了，是因为从实例需要设置一下才能查询。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">myset:SECONDARY&gt; db.getMongo().setSlaveOk();</span><br><span class="line">myset:SECONDARY&gt; show dbs;</span><br><span class="line">admin   <span class="number">0.000</span>GB</span><br><span class="line">config  <span class="number">0.000</span>GB</span><br><span class="line">local   <span class="number">0.000</span>GB</span><br><span class="line">mytest  <span class="number">0.000</span>GB</span><br><span class="line">test    <span class="number">0.000</span>GB</span><br><span class="line">myset:SECONDARY&gt; db.article.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a52221989c0d47f8598d0ad"</span>), <span class="string">"title"</span> : <span class="string">"MongoDB应用开发实战"</span>, <span class="string">"author"</span> : <span class="string">"zhangsan"</span>, <span class="string">"creationDate"</span> : ISODate(<span class="string">"2018-01-07T13:35:21.111Z"</span>) &#125;</span><br></pre></td></tr></table></figure>
<h2 id="添加副本集"><a href="#添加副本集" class="headerlink" title="添加副本集"></a>添加副本集</h2><p><code>rs.add(&#39;host:port&#39;)</code></p>
<h2 id="删除副本集"><a href="#删除副本集" class="headerlink" title="删除副本集"></a>删除副本集</h2><p><code>rs.remove(&#39;host:port&#39;)</code></p>
<h2 id="重新配置"><a href="#重新配置" class="headerlink" title="重新配置"></a>重新配置</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> config = rs.config();</span><br><span class="line"></span><br><span class="line">rs....</span><br><span class="line"></span><br><span class="line">rs.reconfig(config);</span><br></pre></td></tr></table></figure>
<h1 id="监控-mongostat"><a href="#监控-mongostat" class="headerlink" title="监控-mongostat"></a>监控-mongostat</h1><p><strong>mongodb</strong>提供了一个mongostat命令用于监控mongodb服务器。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">➜  ~ mongostat --<span class="built_in">help</span></span><br><span class="line">Usage:</span><br><span class="line">  mongostat &lt;options&gt; &lt;polling interval <span class="keyword">in</span> seconds&gt;</span><br><span class="line"></span><br><span class="line">Monitor basic MongoDB server statistics.</span><br><span class="line"></span><br><span class="line">See http://docs.mongodb.org/manual/reference/program/mongostat/ <span class="keyword">for</span> more information.</span><br></pre></td></tr></table></figure>
<p>监控副本集的命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">➜  ~ mongostat --host=myset/localhost:28010,localhost:28011,localhost:28012</span><br><span class="line">           host insert query update delete getmore <span class="built_in">command</span> dirty used flushes vsize   res qrw arw net_in net_out conn   <span class="built_in">set</span> repl                time</span><br><span class="line">localhost:28010     *0    *0     *0     *0       0     3|0  0.0% 0.0%       0 4.94G 39.0M 0|0 1|0   437b   53.4k    3 myset  SEC Jan 16 12:18:50.342</span><br><span class="line">localhost:28011     *0    *0     *0     *0       0     3|0  0.0% 0.0%       0 4.97G 39.0M 0|0 1|0   432b   52.8k    5 myset  PRI Jan 16 12:18:50.342</span><br></pre></td></tr></table></figure>
<h1 id="关于副本集的原理分析："><a href="#关于副本集的原理分析：" class="headerlink" title="关于副本集的原理分析："></a>关于副本集的原理分析：</h1><ol>
<li>副本集有且只有一台机器是primary，primary与secondary之间的数据复制是异步进行的，并且通过oplog进行。</li>
<li>副本集中的机器数最好为奇数。</li>
<li>Primary机器接收所有的写操作（无法改变的），我们可以配置read preference，使得读操作可以发生在secondary机器上。如果读操作发生在primary机器上，那么机器就是强一致性的；</li>
<li>副本集中最多有50台机器，之前的版本最多有12台机器。如果超过了50台，那么只能使用Master-Slave方式。不过如果使用Master-Slave方式，那么就失去了自动化的failover机制。</li>
<li>Arbiter机器（仲裁机器），它本身并不存放数据库数据，仅提供选举功能。</li>
<li>不要将arbiter机器放在primary或是secondary机器上。</li>
<li><p>对于secondary机器，可以进行如下配置：</p>
<ol>
<li>禁止某台secondary机器成为primary机器，priority为0。</li>
<li>禁止客户端读取某台secondary机器的数据，隐藏成员。</li>
<li>仅记录历史快照的secondary，延迟成员。比如说延迟一小时</li>
</ol>
</li>
<li>最常见的secondary机器依然是进行数据异步复制与保持系统高可用的形式。</li>
<li>副本集中最多有50台机器，其中<strong>具有投票功能</strong>的机器数量最多是7台。</li>
<li>Priority为0的机器：无法成为primary。不能触发一个选举</li>
<li>关于MongoDB的读写分离：        <ol>
<li>如果进行读写分离，那么要注意到读会有延迟</li>
<li>secondary机器要通过oplog异步复制primary机器的数据，因此从整体来看，primary与secondary机器的读速度是大体相当的。</li>
<li>默认情况下，MongoDB的读写都是在primary上进行的。</li>
</ol>
</li>
<li>关于Read preference：        <ol>
<li>Primary（默认值）</li>
<li>primaryPreferred</li>
<li>secondary</li>
<li>secondaryPreferred</li>
<li>nearest（网络延迟最少的）</li>
</ol>
</li>
<li>关于延迟成员（delayed member）        <ol>
<li>延迟成员的priority必须为0，表示它无法成为primary。</li>
<li>延迟成员也是隐藏成员，应用是无法通过延迟成员查询数据的。</li>
<li>可以对primary的选举进行投票。</li>
</ol>
</li>
<li>请确保副本集中成员的个数为奇数，如果是偶数的话，请添加一个arbiter成员。</li>
<li>关于MongoDB的投票与故障恢复：        <ol>
<li>MongoDB投票要求投票时系统中可用的机器数量要是全体副本集成员个数的大多数。</li>
<li>如果副本集中有3台机器，那么有几台机器宕掉还可以确保MongoDB副本集可以正常使用？2台。</li>
<li>如果副本集中有4台机器，那么有几台机器宕掉还可以确保MongoDB副本集可以正常使用？3台。</li>
<li>如果副本集中有5台机器，那么有几台机器宕掉还可以确保MongoDB副本集可以正常使用？3台。</li>
<li>如果副本集中有6台机器，那么有几台机器宕掉还可以确保MongoDB副本集可以正常使用？4台。</li>
<li>如果副本集中有7台机器，那么有几台机器宕掉还可以确保MongoDB副本集可以正常使用？4台。</li>
</ol>
</li>
<li>向副本集中添加成员并不总是会确保系统的故障恢复能力，不过这样做可以实现一些额外的功：备份、统计报表等。</li>
</ol>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mongo/" rel="tag"># Mongo</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/07/mongo4/" rel="next" title="MongoDB4-GridFS、Capped Collections、索引与查询计划">
                <i class="fa fa-chevron-left"></i> MongoDB4-GridFS、Capped Collections、索引与查询计划
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/17/mongo6/" rel="prev" title="MongoDB6-分片">
                MongoDB6-分片 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#副本集"><span class="nav-number">1.</span> <span class="nav-text">副本集</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是复制"><span class="nav-number">1.1.</span> <span class="nav-text">什么是复制?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB复制原理"><span class="nav-number">1.2.</span> <span class="nav-text">MongoDB复制原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#副本集特征："><span class="nav-number">1.3.</span> <span class="nav-text">副本集特征：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB副本集配置"><span class="nav-number">1.4.</span> <span class="nav-text">MongoDB副本集配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#插入数据"><span class="nav-number">1.5.</span> <span class="nav-text">插入数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#添加副本集"><span class="nav-number">1.6.</span> <span class="nav-text">添加副本集</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除副本集"><span class="nav-number">1.7.</span> <span class="nav-text">删除副本集</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重新配置"><span class="nav-number">1.8.</span> <span class="nav-text">重新配置</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#监控-mongostat"><span class="nav-number">2.</span> <span class="nav-text">监控-mongostat</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#关于副本集的原理分析："><span class="nav-number">3.</span> <span class="nav-text">关于副本集的原理分析：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
